// pages/goods_detail/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({
  data: {
    goodsObj: {}
  },
  goods_id: 0,
  onLoad: function(options) {
    const { goods_id } = options;
    console.log(goods_id);
    this.goods_id = goods_id;
    this.getGoodsDetail(goods_id);
  },
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({
      url: "/goods/detail",
      data: { goods_id }
    });
    console.log(goodsObj);
    this.setData({
      goodsObj: {
        goods_id: goodsObj.goods_id,
        pics: goodsObj.pics,
        goods_price: goodsObj.goods_price,
        goods_name: goodsObj.goods_name,
        goods_introduce: goodsObj.goods_introduce
      }
    });
  },
  handlePreviewImg(e) {
    const urls = this.data.goodsObj.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    console.log(e);
    wx.previewImage({
      urls,
      current
    });
  },
  handleCartAdd(e) {
    const cart = wx.getStorageSync("cart") || [];
    const { id } = e.currentTarget.dataset;
    const index = cart.findIndex(v => v.goods_id === id);

    if (index == -1) {
      this.data.goodsObj.num = 1;
      this.data.goodsObj.check = true;
      cart.push(this.data.goodsObj);
    } else {
      cart[index].num++;
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: "商品添加成功",
      icon: "success",
      mask: true
    });
  }
});
